<?
if (eregi(basename( __FILE__ ), $_SERVER['PHP_SELF'])) {
	print "<h1>Incorrect access</h1>You cannot access this file directly.";
	exit();
}
//TuanNK 20090113


//maybe we create new function for handling this
function init_session_cookies($path="/", $domain="") {
  if ($domain=='localhost') $domain='';
  if (function_exists('session_set_cookie_params')) {
    session_set_cookie_params(0, $path, $domain);
  } else {
    ini_set('session.cookie_lifetime', '0');
    ini_set('session.cookie_path', $path);
    ini_set('session.cookie_domain', $domain);
  }
}

$cookie_path = '/';

if(eregi("muachung", $_SERVER['HTTP_HOST'])){
	$cookie_domain = '.muachung.vn'; //or any valid domain
}
else{
	$cookie_domain = "localhost";
}


//$session_save_path = "tcp://$host:$port?persistent=1&weight=2&timeout=2&retry_interval=10,  ,tcp://$host:$port  ";
$session_save_path = "tcp://".MEMCACHE_SESSION_HOST.":".MEMCACHE_SESSION_PORT."?persistent=1&weight=2&timeout=2&retry_interval=10,  ,tcp://".MEMCACHE_SESSION_HOST.":".MEMCACHE_SESSION_PORT."  ";

if (defined('DEBUG') && DEBUG && class_exists('CGlobal') && isset($start_rb)){
	global $start_rb;
	$mtime = microtime();
	$mtime = explode(" ",$mtime);
	$mtime = $mtime[1] + $mtime[0];
	$end_rb = $mtime;			
	$load_time = round(($end_rb - $start_rb),5)."s";					 		
	CGlobal::$conn_debug.= " <b>Connect to Memcache session server : ".MEMCACHE_SESSION_HOST." : ".MEMCACHE_SESSION_PORT." </b> [in $load_time]<br>\n";
}			
		
init_session_cookies($cookie_path, $cookie_domain);
//ini_set('session.gc_divisor',100);
//ini_set('session.gc_probability',    1);	
ini_set('session.gc_maxlifetime', _SESS_TIME_EXPIRE);
ini_set('session.save_handler', 'memcache');
ini_set('session.save_path', $session_save_path);

// below sample main
session_start();
//session_regenerate_id(true);

if(basename($_SERVER['PHP_SELF'])=='index.php'){
	function update_user_online(){
		$session_id = session_id();
		 
		$page     ='';
		$page_id  =0;
		
		$user_id   = isset($_SESSION[MEMCACHE_ID.'user_id'])?(int)$_SESSION[MEMCACHE_ID.'user_id']:0;
		$user_name = isset($_SESSION['user_name'])?$_SESSION['user_name']:0;
    	
		if(class_exists('Layout')){
			$page		=Layout::$page['name'];
			$page_id	=(int)Layout::$page['id'];
		}
		
		if(($page=='product') && isset($_GET['id']) && $_GET['id']){
			$item_id=(int)$_GET['id'];
		}
		else{
			$item_id=0;
		}
		
		if(in_array(basename($_SERVER['PHP_SELF']),array('ebxml.php','ajax.php','captcha.php'))){
			$ref_url='';
		}
		else{
			FunctionLib::check_uri();	
			$ref_url=CGlobal::$query_string;
		}
		
		$sql = "SELECT  session_referer, page, page_id, item_id FROM "._SESS_TABLE." WHERE session_id = '$session_id'";
	    $result = DB::query($sql,__LINE__.__FILE__);
	   
	    if (mysql_num_rows($result)) {
	        $s_row = mysql_fetch_assoc($result);
	    }
	    else{
	    	 $s_row = array();
	    }
		
		if($s_row){
			if($ref_url=='' || in_array(basename($_SERVER['PHP_SELF']),array('ebxml.php','ajax.php','captcha.php'))){
	    		$ref_url=stripslashes($s_row['session_referer']);
	    	}
			
			if(!$page) 					$page 		= $s_row['page'] ;
			if(!$page_id) 				$page_id 	= (int)$s_row['page_id'] ;
			if(!$item_id) 				$item_id 	= (int)$s_row['item_id'] ;
			
			$sql = "UPDATE "._SESS_TABLE." SET
											  	session_expires = ".time().", 
											  	session_referer = '".addslashes($ref_url)."',
											  	session_ip 		= '".$_SERVER['SERVER_ADDR'].'::'.$_SERVER['REMOTE_ADDR']."', 
											  	page 			= '$page',	
											  	page_id 		= $page_id,
											  	item_id 		= $item_id,
											  	user_id 		= '$user_id',
											  	user_name		= '$user_name'
											WHERE session_id 	= '$session_id'";
		}
		else{
			$sql = "INSERT INTO "._SESS_TABLE." 
							  (
							  	session_id, 
							  	session_expires,  
							  	session_referer, 
							  	session_ip,   
							  	page,  
							  	page_id, 
							  	item_id, 
							  	user_id,  
							  	user_name
							  	) 
	                   VALUES (
	                   			'$session_id', 				
	                   			".time().", 			
	                   			'".addslashes($ref_url)."', 	   
	                   			'".$_SERVER['SERVER_ADDR'].'::'.$_SERVER['REMOTE_ADDR']."',	
	                   			'$page',	  
	                   			$page_id,		   
	                   			$item_id, 	  
	                   			$user_id ,		
	                   			'$user_name')";
		}
	                   
		DB::query($sql,__LINE__.__FILE__);
		
		if(User::is_login() && MEMCACHE_ON){//Nếu đã đăng nhập
			$user = User::$current->data;
			if($user && !isset($user['last_login']) || (isset($user['last_login']) && $user['last_login']<(TIME_NOW-300))){
				DB::query("UPDATE ".T_ACCOUNTS." SET last_login=".TIME_NOW." WHERE id={$user['id']}");
				
				$user_memcache = memcacheLib::do_get("user:{$user['id']}");
				if($user_memcache){
					$user_memcache['last_login'] = TIME_NOW;
					memcacheLib::do_put("user:{$user['id']}", $user_memcache);
				}
			}
		}
	}
	
	//register_shutdown_function("update_user_online");
}
?>